<!--
 * @Author: “ChengNan” 1429323234@qq.com
 * @Date: 2024-01-09 14:20:58
 * @LastEditors: “ChengNan” 1429323234@qq.com
 * @LastEditTime: 2024-06-07 15:35:10
 * @FilePath: /src/views/1.tableSelect/tableSelect.vue
 * @Description: table跨页选
-->
<template>
  <div>
    <h1>table跨页选</h1>

    <Table 
      ref="selection"
      border 
      :columns="columns" 
      :data="data" 
      style="width: 400px;margin: 0 auto;"
      @on-select="select"
      @on-select-cancel="selectCancel"
      @on-select-all="selectAll"
      @on-select-all-cancel="selectAllCancel"
      @on-selection-change="checkedSetUpdate"
    ></Table>
    
    <Checkbox v-model="single" @on-change="handleSelectAll">全选</Checkbox>

    <Page 
      style="margin-top: 20px;" 
      :total="8" 
      @on-change="changePageNo" 
      :page-size="4" />
  </div>
</template>

<script>
export default {
  name: 'tableSelect',
  data() {
    return {
      columns: [
        { type: 'selection', width: 60, align: 'center' },
        { title: 'id', key: 'id' },
        { title: 'Name', key: 'name' },
        { title: 'Age', key: 'age' },
      ],
      data: [],
      // 页
      pageNo: 1,
      // 全选check状态
      single: false,
      // checkSet
      checkedSet: new Set(),
    }
  },
  mounted () {
    this.checkedSet.add(1)
    this.checkedSet.add(2)
    this.changePageNo(1)
  },
  methods: {
    // 页码切换
    changePageNo(val) {
      this.pageNo = val

      if (this.pageNo == 1) {
        this.data = [
          { id: 1, name: '张1', age: 18 },
          { id: 2, name: '张2', age: 24 },
          { id: 3, name: '张3', age: 30 },
          { id: 4, name: '张4', age: 26 }
        ]
      }

      if (this.pageNo == 2) {
        this.data = [
          { id: 5, name: '张5', age: 18 },
          { id: 6, name: '张6', age: 24 },
          { id: 7, name: '张7', age: 30 },
          { id: 8, name: '张8', age: 26 }
        ]
      }

      this.checkedSetUpdate()
    },
    // 选中事件
    select(selection, row) {
      this.checkedSet.add(row.id)
    },
    // 取消选中
    selectCancel(selection, row) {
      this.checkedSet.delete(row.id)
    },
    // 全选
    selectAll(selection) {
      this.data.forEach(el => this.checkedSet.add(el.id))
    },
    // 取消全选
    selectAllCancel(selection) {
      this.data.forEach(el => this.checkedSet.delete(el.id))
    },
    // 更新选中项
    checkedSetUpdate(selection) {
      this.data.forEach(el => this.$set(el, '_checked', this.checkedSet.has(el.id)))
      this.single = this.data.every(el => el._checked)
    },

    // 全选按钮
    handleSelectAll(status) {
      this.$refs.selection.selectAll(status);
    },
  }
}
</script>

<style lang="scss" scoped></style>